package com.yun.controller.loginRegister;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @RequestMapping("/toLogin")
    public String login(){
        return "login";
    }


    @RequestMapping("/dLogin")
    public String dLogin(@RequestParam(value = "username")String username,
                        @RequestParam("password")String password,
                        Model model, HttpSession session) {
        /*获取当前用户*/
        Subject subject = SecurityUtils.getSubject();
        /*封装用户登录数据*/
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
                subject.login(token);//执行登录方法
                session.setAttribute("loginUser",username);
                return "main";
            }catch (UnknownAccountException e){//用户名不存在
                model.addAttribute("msg","用户名不存在,请重新输入或者注册");
                return "login";
            }catch (IncorrectCredentialsException e){//密码不存在
                model.addAttribute("msg","密码不存在");
                return "login";
            }
        }

    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session){
        session.invalidate();
        return "main";
    }
}
